package com.example.searchbackend.once;

import cn.hutool.http.HttpUtil;
import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.time.Duration;
import java.util.Set;

/**
 * 爬取图片
 * @author 米饭好好吃
 */
public class CrawlImages {
    public static void main(String[] args) throws InterruptedException, IOException {
        WebDriverManager.chromedriver().setup();
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--remote-allow-origins=*");
        WebDriver driver = new ChromeDriver(options);
        // 1. 打开百度首页
        driver.get("https://www.baidu.com");
        // 2. 输入关键词
        String keyword = "米饭";
        driver.findElement(By.cssSelector("#kw")).sendKeys(keyword);
        // 3. 点击搜索按钮
        driver.findElement(By.cssSelector("#su")).click();
        // 4. 找到图片点击进入
        WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(3));
        wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("#\\31  > div > h3 > a")));
        driver.findElement(By.cssSelector("#\\31  > div > h3 > a")).click();
        // 5. 切换标签页
        Set<String> handles = driver.getWindowHandles();
        String curHandle = driver.getWindowHandle();
        for (String handle : handles) {
            if (!handle.equals(curHandle)) {
                driver.switchTo().window(handle);
            }
        }
        // 6. 批量爬取图片
        for (int childNo = 1; childNo <= 20; childNo++) {
            String imgCssSelector = String.format("#imgid > div:nth-child(1) > ul > li:nth-child(%d) > div > div.imgbox-border > a > img", childNo);
            String textCssSelector = String.format("#imgid > div > ul > li:nth-child(%d) > a", childNo);
            wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector(imgCssSelector)));
            String srcImgUrl = driver.findElement(By.cssSelector(imgCssSelector)).getAttribute("data-imgurl");
            wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector(textCssSelector)));
            String text = driver.findElement(By.cssSelector(textCssSelector)).getText();
            OutputStream outputStream = new FileOutputStream("./images/" + childNo + ".png");
            HttpUtil.download(srcImgUrl, outputStream, false);
        }
        driver.quit();
    }
}
